﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace org.xisoft.game.utils.game.algorithms
{
    public class CachedAlgorithm<AI,Broad> : AiAlgorithm<Broad>
        where AI : AiAlgorithm<Broad>, new()
        where Broad: ChessBoardBase
    {
        private readonly AI algorithm;
        public CachedAlgorithm(AI algorithm)
        {
            this.algorithm = algorithm;
        }

        public CachedAlgorithm()
            :this(new AI())
        {

        }

        MoveAction cacheMoveAction;
        public override MoveAction Search(Broad broad, int depth)
        {
            if (cacheMoveAction == null)
                cacheMoveAction = algorithm.Search(broad, depth);
            return cacheMoveAction;
        }

        public override void DoNext(Broad broad, MoveAction moveAction)
        {
            if (cacheMoveAction != null)
            {
                if (moveAction.FromX != cacheMoveAction.FromX || moveAction.FromY != cacheMoveAction.FromY || moveAction.ToX != cacheMoveAction.ToX || moveAction.ToY != cacheMoveAction.ToY)
                    cacheMoveAction = null;
                else
                    cacheMoveAction = cacheMoveAction.Next;
            }
            algorithm.DoNext(broad, moveAction);
        }

        public override List<MoveAction> GetAllCanMoves(Broad broad)
        {
            return algorithm.GetAllCanMoves(broad);
        }

        public override bool? GetWinColor(Broad chessBoard)
        {
            return algorithm.GetWinColor(chessBoard);
        }
    }
}
